package com.atguigu.srb.core.controller;


import com.alibaba.fastjson.JSON;
import com.atguigu.srb.base.util.JwtUtils;
import com.atguigu.srb.common.exception.Assert;
import com.atguigu.srb.common.result.R;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.pojo.vo.InvestVO;
import com.atguigu.srb.core.service.LendItemService;
import com.atguigu.srb.core.service.TransFlowService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 标的出借记录表 前端控制器
 * </p>
 *
 * @author LiLi
 * @since 2021-09-23
 */
@Api("标的投资")
@Slf4j
@RestController
@RequestMapping("/api/core/lendItem")
public class LendItemController {
    @Autowired
    LendItemService lendItemService;
    @Autowired
    TransFlowService transFlowService;
    @ApiOperation("会员投资提交数据")
    @PostMapping("/auth/commitInvest")
    public R commitInvest(@RequestBody InvestVO investVO, HttpServletRequest request){
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        String userName = JwtUtils.getUserName(token);
        investVO.setInvestUserId(userId);
        investVO.setInvestName(userName);
        //构建充值自动提交表单
        String formStr = lendItemService.commitInvest(investVO);
        return R.ok().data("formStr",formStr);
    }
    @ApiOperation("会员投资异步回调")
    @PostMapping("/notify")
    public String notify(HttpServletRequest request) {
        Map<String, Object> paramMap = RequestHelper.switchMap(request.getParameterMap());

        String agentBillNo = (String) paramMap.get("agentBillNo");
        //幂等性校验
        boolean b = transFlowService.isSaveTransFlow(agentBillNo);
        Assert.isTrue(b, ResponseEnum.RESPONSE_CHONGFU);
        if(RequestHelper.isSignEquals(paramMap)){//先判断回调签名是否正确
            if("0001".equals((String)paramMap.get("resultCode"))){//再判断回调码
                lendItemService.hfbNotify(paramMap);
            }
        }
        return "success";

    }



}

